<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.username" clearable class="filter-item" style="width: 200px;" placeholder="请输入用户名" />
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号" />
      <el-select v-model="listQuery.brokerage" style="width: 200px" :clearable="true" class="filter-item" placeholder="请选择代理状态">
        <el-option v-for="(key, value) in brokerageDic" :key="key" :label="key" :value="value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" width="100px" label="用户ID" prop="id" sortable />
      <el-table-column align="center" label="用户名" prop="username" />
      <el-table-column align="center" label="昵称" prop="nickname" />
      <el-table-column align="center" label="手机号码" prop="mobile" />
      <el-table-column align="center" label="性别" prop="gender">
        <template slot-scope="scope">
          <el-tag>{{ genderDic[scope.row.gender] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="生日" prop="birthday" />
      <el-table-column align="center" label="用户等级" prop="userLevel">
        <template slot-scope="scope">
          <el-tag>{{ levelDic[scope.row.userLevel] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="推荐人" prop="shareUserName" />
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag>{{ statusDic[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="代理状态" prop="brokerage">
        <template slot-scope="scope">
          <el-tag>{{ brokerageDic[scope.row.brokerage] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册时间" prop="addTime" />
      <el-table-column align="center" label="更新时间" prop="updateTime" />
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/user/detail']" type="primary" size="mini" @click="handleUserDetail(scope.row)">会员详情</el-button>
          <el-button v-if="scope.row.brokerage==1" v-permission="['POST /admin/user/approveAgency']" type="primary" size="mini" @click="handleApproveAgency(scope.row)">审批代理</el-button>
          <el-button v-else-if="scope.row.brokerage==2" v-permission="['GET /admin/user/detailApprove']" type="primary" size="mini" @click="handleDetailApprove(scope.row)">代理详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailApproveDialogVisible" title="代理详情" width="700">
      <el-form :data="agencyDetail" label-position="left">
        <el-form-item label="佣金比例(%)">
          <span>{{ agencyDetail.settlementRate }}</span>
        </el-form-item>
        <el-form-item label="推广二维码">
          <img :src="agencyDetail.shareUrl" width="300">
        </el-form-item>
        <el-button v-permission="['GET /admin/user/cancelApprove']" type="primary" @click="handleCancelAgency(agencyDetail)">取消代理</el-button>
        <el-button type="primary" @click="handleCloseDialog">关闭</el-button>
      </el-form>
    </el-dialog>
    <!-- 代理审批 -->
    <el-dialog :visible.sync="approveDialogVisible" title="代理审批">
      <el-form ref="approveForm" :model="approveForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="佣金比例(%)" prop="settlementRate">
          <el-input v-model="approveForm.settlementRate" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog title="编辑" :visible.sync="dialogUserFormVisible">
      <el-form ref="userDetail" :model="userDetail" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userDetail.username" readonly />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userDetail.nickname" readonly />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userDetail.mobile" />
        </el-form-item>
        <el-form-item label="注册时间" prop="addTime">
          <el-input v-model="userDetail.addTime" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-tag>{{ statusDic[userDetail.status] }}</el-tag>
        </el-form-item>
        <el-form-item label="代理状态" prop="brokerage">
          <el-tag>{{ brokerageDic[userDetail.brokerage] }}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserDetail(userDetail)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, approveAgency, detailApprove, cancelAgency, updateUser } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        mobile: undefined,
        brokerage: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      downloadLoading: false,
      genderDic: ['未知', '男', '女'],
      levelDic: ['普通用户', 'VIP用户', '高级VIP用户'],
      statusDic: ['可用', '禁用', '注销'],
      brokerageDic: ['非代理', '申请中', '代理'],
      detailApproveDialogVisible: false,
      dialogUserFormVisible: false,
      agencyDetail: {},
      approveDialogVisible: false,
      approveForm: {
        userId: undefined,
        settlementRate: undefined
      },
      userDetail: {
        id: undefined,
        username: '',
        nickname: '',
        mobile: undefined,
        status: 0,
        addTime: undefined,
        shareUserId: 0
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCloseDialog() {
      this.detailApproveDialogVisible = false
      this.approveDialogVisible = false
    },
    handleDetailApprove(row) {
      this.agencyDetail = {
        userId: undefined,
        shareUrl: undefined,
        settlementRate: 5
      }
      detailApprove(row.id).then(response => {
        this.agencyDetail = response.data.data
      })
      this.detailApproveDialogVisible = true
    },
    handleApproveAgency(row) {
      this.approveForm.userId = row.id

      this.approveDialogVisible = true
      this.$nextTick(() => {
        this.$refs['approveForm'].clearValidate()
      })
    },
    handleCancelAgency(agencyDetail) {
      this.approveForm.userId = agencyDetail.userId
      cancelAgency(this.approveForm).then(response => {
        this.$notify.success({
          title: '成功',
          message: '取消代理成功'
        })
        this.getList()
      }).catch(response => {
        this.$notify.error({
          title: '取消代理失败',
          message: response.data.errmsg
        })
      })
    },
    confirmApprove() {
      this.$refs['approveForm'].validate((valid) => {
        if (valid) {
          approveAgency(this.approveForm).then(response => {
            this.approveDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '审批成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '审批失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '手机号码', '性别', '生日', '状态', '代理状态', '注册时间']
        const filterVal = ['username', 'mobile', 'gender', 'birthday', 'status', 'brokerage', 'addTime']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '用户信息')
        this.downloadLoading = false
      })
    },
    handleUserDetail(row) {
      this.userDetail = Object.assign({}, row)
      this.dialogUserFormVisible = true
      this.$nextTick(() => {
        this.$refs['userDetail'].clearValidate()
      })
    },
    updateUserDetail() {
      this.$refs['userDetail'].validate((valid) => {
        if (valid) {
          updateUser(this.userDetail).then(response => {
            this.dialogUserFormVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '更新失败',
              message: response.data.errmsg
            })
          })
        }
      })
    }
  }
}
</script>
